<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="jobname">
        <el-input
          v-model="queryParams.jobname"
          placeholder="请输入任务名称"
          style="width: 240px"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执行状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择执行状态" style="width: 240px" clearable>
          <el-option
            v-for="dict in dict.type.gg_job_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="daterangeKssj"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="是否有效" prop="yxbz">
        <el-select v-model="queryParams.yxbz" placeholder="请选择任务有效状态" style="width: 240px" clearable>
          <el-option
            v-for="dict in dict.type.gg_job_valid"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="可否并发" prop="sfbf">
        <el-select v-model="queryParams.sfbf" placeholder="请选择任务是否可并发" style="width: 240px" clearable>
          <el-option
            v-for="dict in dict.type.gg_job_sfkbf"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['job:jobmonitor:edit']"
        >修改</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="jobmonitorList" @selection-change="handleSelectionChange" height="330px">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center">
        <template slot-scope="scope">
          <span>{{ (pageParams.current-1)*pageParams.size + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务名称" align="center" prop="jobname" min-width="120" />
      <el-table-column label="调度策略" align="center" prop="crontime" min-width="120" />
      <el-table-column label="可否并发" align="center" prop="sfbf">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gg_job_sfkbf" :value="scope.row.sfbf"/>
        </template>
      </el-table-column>
      <el-table-column label="线程数量" align="center" prop="threadnum" />
      <el-table-column label="超时时间" align="center" prop="timeout" />
      <el-table-column label="开始时间" align="center" prop="kssj" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.kssj, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="jssj" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.jssj, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否有效" align="center" prop="yxbz">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gg_job_valid" :value="scope.row.yxbz"/>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['job:jobmonitor:edit']"
          >修改</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['job:jobmonitor:list']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleRun" icon="el-icon-caret-right"
                v-hasPermi="['job:jobmonitor:list']">执行一次</el-dropdown-item>
              <el-dropdown-item command="handleView" icon="el-icon-view"
                v-hasPermi="['job:jobmonitor:list']">任务详细</el-dropdown-item>
              <el-dropdown-item command="handleJobLog" icon="el-icon-s-operation"
                v-hasPermi="['job:jobmonitor:list']">调度日志</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pageParams.current"
      :limit.sync="pageParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改定时任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="jobname">
          <el-input v-model="form.jobname" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="调度策略" prop="crontime">
          <el-input v-model="form.crontime" placeholder="请输入调度策略" />
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="超时时间" prop="timeout">
          <el-input v-model="form.timeout" placeholder="请输入超时时间，单位分钟" />
        </el-form-item>
        <el-form-item label="可否并发" prop="sfbf">
          <template>
            <dict-tag :options="dict.type.gg_job_sfkbf" :value="form.sfbf"/>
          </template>
        </el-form-item>
        <el-form-item label="线程数量" prop="threadnum">
          <el-input v-model="form.threadnum" placeholder="请输入线程数量" :disabled="!(form.sfbf  === 'Y')" />
        </el-form-item>
        <el-form-item label="是否有效" prop="yxbz">
          <el-radio-group v-model="form.yxbz">
            <el-radio
              v-for="dict in dict.type.gg_job_valid"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 任务详细信息 -->
    <el-dialog title="任务详细" :visible.sync="openView" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务名称：">{{ form.jobname }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行类名：">{{ form.jobclass }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调度策略：">{{ form.crontime }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有效状态：">
              <template>
                <dict-tag :options="dict.type.gg_job_valid" :value="form.yxbz"/>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="超时时间：">{{ form.timeout }}{{ '分钟' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="可否并发：">
              <template>
                <dict-tag :options="dict.type.gg_job_sfkbf" :value="form.sfbf"/>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="并发数量：">{{ form.threadnum }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务描述：">{{ form.description }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行状态（最近一次）：" label-width="180px">
              <template>
                <dict-tag :options="dict.type.gg_job_status" :value="form.status"/>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开始时间（最近一次）：" label-width="180px">{{ form.kssj }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="结束时间（最近一次）：" label-width="180px">{{ form.jssj }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="错误信息（最近一次）：" v-if="form.status !== undefined && form.status !== null && form.status === '3'">{{ form.cwxx }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listJobmonitor, getJobmonitor, updateJobmonitor, runJob } from "@/api/job/jobmonitor";
import { Message } from 'element-ui'

export default {
  name: "Jobmonitor",
  dicts: ['gg_job_valid', 'gg_job_sfkbf', 'gg_job_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 定时任务表格数据
      jobmonitorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详细弹出层
      openView: false,
      // 是否有效时间范围
      daterangeKssj: [],
      // 分页参数
      pageParams: {
        current: 1,
        size: 10,
      },
      // 查询参数
      queryParams: {
        jobclass: null,
        jobname: null,
        status: null,
        kssj: null,
        yxbz: null,
        sfbf: null,
        beginKssj: null,
        endKssj: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {},
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.handleQuery()
    })
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.pageParams.current = 1;
      this.getList();
    },
    /** 查询定时任务列表 */
    getList() {
      this.loading = true;
      if (null != this.daterangeKssj && '' != this.daterangeKssj) {
        this.queryParams["beginKssj"] = this.daterangeKssj[0];
        this.queryParams["endKssj"] = this.daterangeKssj[1];
      } else {
        this.queryParams["beginKssj"] = null;
        this.queryParams["endKssj"] = null;
      }
      listJobmonitor(this.pageParams,this.queryParams).then(response => {
        this.jobmonitorList = response.page.records;
        this.total = response.page.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        jobclass: null,
        triggername: null,
        triggergroup: null,
        jobname: null,
        crontime: null,
        description: null,
        threadnum: null,
        timeout: null,
        status: null,
        kssj: null,
        jssj: null,
        cwxx: null,
        yxbz: null,
        sfbf: null
      };
      this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeKssj = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jobclass);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      var jobclassUpdate = row.jobclass;
      if(row.isTrusted){
        jobclassUpdate = this.ids[0];
      }
      this.queryParams["jobclass"] = jobclassUpdate;
      getJobmonitor(this.queryParams).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改定时任务";
        this.queryParams["jobclass"] = null;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateJobmonitor(this.form).then(response => {
            if(response.code==='200'&&response.data>0) {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }else {
              this.$modal.msgError("修改失败");
              this.open = false;
            }
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('job/jobmonitor/export', {
        ...this.queryParams
      }, `jobmonitor_${new Date().getTime()}.xlsx`)
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleRun":
          this.handleRun(row);
          break;
        case "handleView":
          this.handleView(row);
          break;
        case "handleJobLog":
          this.handleJobLog(row);
          break;
        default:
          break;
      }
    },
    /* 立即执行一次 */
    handleRun(row) {
      if (row.yxbz !== 'Y') {
        Message({ message: "无效任务，无法执行！", type: 'warning', duration: 3 * 1000 });
      } else if (row.status === '1') {
        Message({ message: "任务运行中，不需要再次执行！", type: 'warning', duration: 3 * 1000 });
      } else {
        this.$modal.confirm('确认要立即执行一次"' + row.jobname + '"任务吗？').then(function() {
          return runJob({jobClass: row.jobclass});
        }).then(() => {
          this.$modal.msgSuccess("执行成功");
        }).catch(() => {});
      }
    },
    /** 任务详细信息 */
    handleView(row) {
      this.form = row;
      this.openView = true;
    },
    /** 任务日志列表查询 */
    handleJobLog(row) {
      const jobclass = row.jobclass;
      const sfbf = row.sfbf;
      this.$router.push({path:'/monitor/runlog/index', query:{jobclass:jobclass,sfbf:sfbf}});
    }
  }
};
</script>
